package com.example.bloomfilterdemo.guavaUtils;
import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;

/**
 * Created by IntelliJ IDEA2022.3.2
 * @Author: Tenghw
 * @Date: 2023/06/08  20:06
 * @Description: 布隆过滤器测试代码：我们创建了一个最多存放1千万个整数的布隆过滤器，并且我们可以容忍误判的概率为百分之（0.01）
 */
@SuppressWarnings("all")
public class BloomFilterTest {
    /**
     * 预计插入数据的个数
     */
    private static  Integer expectedInsertions = 10000000;
    //private static  Long expectedInsertions = 10000000L;
    /**
     * 误判率
     */
    private static  double fpp = 0.01d;
    /**
     * 布隆过滤器
     */
    private static BloomFilter<Integer> bloomFilter= BloomFilter.create(Funnels.integerFunnel(),expectedInsertions,fpp);
    //private static BloomFilter<Long> bloomFilter= BloomFilter.create(Funnels.longFunnel(),expectedInsertions,fpp);
    public static void main(String[] args) {
        // 插入1千万条数据
        for (int  i=0; i<expectedInsertions; i++){
            bloomFilter.put(i);
        }

        // 用1千万条数据测试误判率
        int count=0;
        for (int i=expectedInsertions; i<expectedInsertions * 2; i++){
            if(bloomFilter.mightContain(i)){
                count++;
            }
        }

        // 输出最终测试误判率
        System.out.println("一共误判了：" + count + "条数据");

        System.out.println("--------------------------------");
        // 判断指定元素是否存在
        System.out.println(bloomFilter.mightContain(-1));
        System.out.println(bloomFilter.mightContain(-2));
        // 将元素添加进布隆过滤器
        bloomFilter.put(-1);
        bloomFilter.put(-2);
        System.out.println(bloomFilter.mightContain(-1));
        System.out.println(bloomFilter.mightContain(-2));
    }
}
